package main.java.indi.zyj.c150.back;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class _08_PermuteUnique {

    List<List<Integer>> res = new LinkedList<>();
    LinkedList<Integer> track = new LinkedList<>();
    boolean[] used;

    public List<List<Integer>> permuteUnique(int[] nums) {
        Arrays.sort(nums);
        used = new boolean[nums.length];
        backtrack(nums);
        return res;
    }


    // 回溯算法主函数
    void backtrack(int[] nums) {

        if (nums.length == track.size()) {
            res.add(new LinkedList<>(track));
        }

        for (int i = 0; i < nums.length; i++) {
            if (used[i]) {
                continue;
            }
            if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) {
                continue;
            }
            track.add(nums[i]);
            used[i] = true;
            backtrack(nums);
            track.removeLast();
            used[i] = false;

        }


    }

    void backtrack(int[] nums, LinkedList<Integer> track) {
        if (track.size() == nums.length) {
            res.add(new LinkedList(track));
            return;
        }

        // 记录之前树枝上元素的值
        // 题目说 -10 <= nums[i] <= 10，所以初始化为特殊值
        int prevNum = -666;
        for (int i = 0; i < nums.length; i++) {
            // 排除不合法的选择
            if (used[i]) {
                continue;
            }
            if (nums[i] == prevNum) {
                continue;
            }

            track.add(nums[i]);
            used[i] = true;
            // 记录这条树枝上的值
            prevNum = nums[i];

            backtrack(nums, track);

            track.removeLast();
            used[i] = false;
        }
    }


}
